package com.csii.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

public class DownLoadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //得到要下在的文件名:UUID_原始文件名.扩展名
        String fileName = request.getParameter("fileName");
        fileName = new String(fileName.getBytes("iso8859-1"),"UTF-8");
        //上传文件保存的父级目录
        String fileSaveRootPath = this.getServletContext().getRealPath("/WEB-INF/upload");
        //通过文件名+特定的算法 定位该文件所在的子级目录
        String fileSavePath = findFileSavePathByFileName(fileSaveRootPath,fileName);
        //得到要下载的文件的完整路径
        File file = new File(fileSavePath+"\\"+fileName);
        //如果文件不存在
        if ( !file.exists()){
            request.setAttribute("message","要下载的文件不存在");
            request.getRequestDispatcher("/message.jsp").forward(request,response);
            return;
        }
        //处理文件名
        String realName = fileName.substring(fileName.indexOf("_")+1);
        //设置响应头,控制浏览器下载该文件
        response.setHeader("content-disposition","attachment;fileName="+URLEncoder.encode(realName,"UTF-8"));
        //读取要下载的文件,保存到文件输入流
        FileInputStream in = new FileInputStream(fileSavePath+"\\"+fileName);
        //创建输出流
        OutputStream out = response.getOutputStream();
        //创建缓冲区
        byte buffer[] = new byte[1024];
        int length = 0;
        //循环将 输入流中的内容 读入到 缓冲区中
        while ( (length = in.read(buffer)) > 0){
            //输出 缓冲区的内容到 浏览器,实现文件下载
            out.write(buffer,0,length);
        }

        //关闭文件输入流
        in.close();
        //关闭输出流
        out.close();

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    /**
     *
     * @param fileSaveRootPath
     * @param fileName
     * @return
     */
    protected String findFileSavePathByFileName(String fileSaveRootPath,String fileName){
        int hashCode = fileName.hashCode();
        int dir1 = hashCode & 0xf;//0-15
        int dir2 = (hashCode & 0xf0)>>4;//0-15
        String dir = fileSaveRootPath+"\\"+dir1+"\\"+dir2;
        File file = new File(dir);
        if ( !file.exists()){
            //创建目录
            file.mkdir();
        }
        return dir;
    }
}

